package com.learn.practice.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;

import org.springframework.web.bind.annotation.*;

import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

@Slf4j
@RestController
@RequiredArgsConstructor
public class EmailController {

    private final JavaMailSender javaMailSender;


    @PostMapping("/sendEmail")
    public boolean sendEmail(@RequestParam("email") String email,
                             @RequestParam("text") String text) {
        try {
            SimpleMailMessage msg = createSimpleMsg(email, text); //createMimeMsg(email, text, "java.png");
            javaMailSender.send(msg);
        } catch (Exception ex) {
            log.error("邮件发送失败：", ex);
            return false;
        }
        return true;
    }

    /**
     * 创建复杂邮件
     * @param email
     * @param text
     * @param attachmentClassPath
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    private MimeMessage createMimeMsg(String email, String text, String attachmentClassPath) throws MessagingException, UnsupportedEncodingException {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg, true);
        mimeMessageHelper.setFrom("libaohome@163.com", "louis");
        mimeMessageHelper.setTo(email);
        mimeMessageHelper.setBcc("libaohome@yeah.net");
        mimeMessageHelper.setSubject("测试附件邮件");
        mimeMessageHelper.setText(text);
        mimeMessageHelper.addAttachment("附件",
                new ClassPathResource(attachmentClassPath));
        return msg;
    }

    /**
     * 创建简单邮件
     * @param email
     * @param text
     * @return
     */
    private SimpleMailMessage createSimpleMsg(String email, String text) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("libaohome@163.com");
        msg.setTo(email);
        msg.setBcc("libaohome@yeah.net");
        msg.setSubject("测试文本邮件");
        msg.setText(text);
        return msg;
    }
}
